package com.sky.server.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.sky.asecpt.anno.Log;
import com.sky.dto.CategoryDTO;
import com.sky.dto.CategoryPageQueryDTO;
import com.sky.entity.Category;
import com.sky.exception.BaseException;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.exception.SqlException;
import com.sky.mapper.CategoryMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.EmployeeMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.pojo.StatusUpdate;
import com.sky.result.PageResult;
import com.sky.server.CategoryServer;
import io.swagger.v3.oas.annotations.servers.Server;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

// @Primary
@Service
@Slf4j
public class CategoryServerImpl implements CategoryServer {


    @Autowired
    private CategoryMapper categoryMapper;

    @Resource
    private RedisTemplate redisTemplate;

    @Autowired
    private SetmealMapper setmealMapper;

    @Autowired
    private DishMapper dishMapper;

    // 根据类型获取分类菜单
    @Override
    public List<Category> listByType(Integer type) {
        return categoryMapper.listByType(type);
    }

    // 分页查询
    @Override
    public PageResult pageEmployee(CategoryPageQueryDTO categoryPageQueryDTO) {
        // 将所有数据获取，使用流来过滤
        List<Category> list = categoryMapper.list();
        if (categoryPageQueryDTO.getName() != null) {
            list = list.stream().filter(category -> category.getName().contains(categoryPageQueryDTO.getName())).collect(Collectors.toList());
        }
        if (categoryPageQueryDTO.getType() != null) {
            list = list.stream().filter(category -> category.getType().equals(categoryPageQueryDTO.getType())).collect(Collectors.toList());
        }
        Long count = (long) list.size();
        List<Category> categoryList = list.stream().skip(((categoryPageQueryDTO.getPage() - 1) * categoryPageQueryDTO.getPageSize())).limit(categoryPageQueryDTO.getPageSize()).collect(Collectors.toList());

        PageResult pageResult = new PageResult();
        pageResult.setTotal(count);
        pageResult.setRecords(categoryList);
        return pageResult;
    }

    // 修改分类状态
    @Override
    public void status(StatusUpdate statusUpdate) {
        try {
            categoryMapper.status(statusUpdate);
        } catch (Exception e) {
            throw new SqlException("状态修改错误");
        }
    }

    @Override
    public void update(CategoryDTO categoryDTO) {
        Category category = new Category();
        BeanUtil.copyProperties(categoryDTO, category);
        categoryMapper.update(category);
    }

    // 添加菜品
    @Override
    public void addCategory(CategoryDTO categoryDTO) {
        try {
            Category category = new Category();
            BeanUtil.copyProperties(categoryDTO, category);
            category.setStatus(1);
            categoryMapper.addCategory(category);
        } catch (Exception e) {
            throw new SqlException("添加分类异常");
        }
    }

    @Override
    public List<Category> list(Object type) {
        List<Category> list = null;
        // key的编排 工程名:模块名:业务场景:特征码
        String key = "sky:admin:categories:" + type;
        if (redisTemplate.hasKey(key)) {
            String jsonStr = (String) redisTemplate.opsForValue().get(key);
            list = JSONUtil.toList(jsonStr, Category.class);
        } else {
            list = categoryMapper.list();
            // 判断type
            if (type != null) {
                list = list.stream().filter(s -> s.getType().equals(type)).collect(Collectors.toList());
            }
            String jsonStr = JSONUtil.toJsonStr(list);
            redisTemplate.opsForValue().set(key, jsonStr);
        }

        return list;
    }

    // 删除分类
    public void deleteById(Long id) {
        // 是否关联了菜品
        Integer count = dishMapper.countByCategoryId(id);
        if (count > 0) {
            // 当前分类下有菜品
            log.info("关联菜品");
            throw new BaseException("删除错误");
        }
        // 是否关联套餐
        count = setmealMapper.countByCategoryId(id);
        if (count > 0) {
            log.info("关联套餐");
            throw new BaseException("删除错误");
        }

        // 删除分类数据
        categoryMapper.deleteById(id);
    }

}

